package com.lagou.edu.code.service.impl;

import com.lagou.edu.code.mapper.LagouAuthCodeMapper;
import com.lagou.edu.code.service.LagouAuthCodeParam;
import com.lagou.edu.code.service.LagouAuthCodeService;
import com.lagou.edu.users.pojo.LagouAuthCode;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

@Service
public class LagouAuthCodeServiceImpl implements LagouAuthCodeService {

    @Autowired
    private LagouAuthCodeMapper lagouAuthCodeMapper;

    @Override
    public LagouAuthCode getAuthCodeByEmailAndTime(LagouAuthCodeParam param) {
        LagouAuthCode authCodeByEmailInCurrent = lagouAuthCodeMapper.getAuthCodeByEmailInCurrent(param);
        return authCodeByEmailInCurrent;
    }

    @Override
    public void saveNewAuthCode(LagouAuthCode code) {
        code.setCreatetime(new Date(System.currentTimeMillis()));
        code.setExpiretime(new Date(System.currentTimeMillis()+10*60*1000));
//        code.setCode(""+(int)((Math.random()*9+1)*100000));
        lagouAuthCodeMapper.insert(code);
    }

    @Override
    public String generateCode() {
        return ""+(int)((Math.random()*9+1)*1000);
    }

    @Override
    public Integer validate(String email, String code) {
        LagouAuthCodeParam param = new LagouAuthCodeParam();
        param.setEmail(email);
        param.setCurrentTime(new Date(System.currentTimeMillis()));
        LagouAuthCode authCodeByEmailAndTime = getAuthCodeByEmailAndTime(param);
        if (authCodeByEmailAndTime == null){
            return 2; //超时或者不存在验证码
        }
        if (!authCodeByEmailAndTime.getCode().equals(code)) {
            // 错误验证码
            return 1;
        }
        return 0;
    }
}
